package com.maple.soa.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 文件上传拦截器，上传文件类型限制
 * @author lijian
 * @date 2020/7/21
 */
@Slf4j
public class UploadInterceptor implements HandlerInterceptor {
    private Long maxSize;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("UploadInterceptor preHandle! {}", maxSize);
        MultipartResolver multipartResolver = new CommonsMultipartResolver();
        if (multipartResolver.isMultipart(request)) {
            log.info("this request is a MultipartHttpServletRequest.");
            MultipartHttpServletRequest multipartRequest = multipartResolver.resolveMultipart(request);
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            fileMap.values().forEach(file -> {
                String filename = file.getOriginalFilename();
                long size = file.getSize();
                String contentType = file.getContentType();
                log.info("upload file: {}, size: {}, content-type: {}", filename, size, contentType);
            });
        }

        return false;
    }

    public Long getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(Long maxSize) {
        this.maxSize = maxSize;
    }
}
